
package controller.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import model.domain.Priority;
import model.domain.Product;

public class ProductConverter implements Converter  {

    public ProductConverter() {
    }


    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value)
    {

        if (value == null || (value.trim().length() == 0))
        {
            return value;
        }

        Product product = new Product();

        String[] splitedString = value.split("::");
        product.setProductID(Integer.parseInt(splitedString[0]));
        product.setPriority(new Priority());
        product.getPriority().setPriorityID(Integer.parseInt(splitedString[1]));
        product.setDescription(splitedString[2]);
        if(splitedString.length > 3)
            product.setComments(splitedString[3].replace('¢', ','));

        return product;
    }

    @Override
      public String getAsString(FacesContext context, UIComponent component, Object value)
      {

       Product product = null;

        if (value instanceof Product)
        {
            product = (Product)value;

            StringBuilder productAsString = new StringBuilder();
            productAsString.append(product.getProductID());
            productAsString.append("::");
            productAsString.append(product.getPriority().getPriorityID());
            productAsString.append("::");
            productAsString.append(product.getDescription());
            productAsString.append("::");
            String tempString = product.getComments();
            if(tempString != null)
                productAsString.append(tempString.replace(',', '¢'));
            String string = productAsString.toString();
            return string;
        }
        return "";
    }

}
